package zoptio.wicket.mooeditable;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.AjaxCallDecorator;
import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton;
import org.apache.wicket.behavior.IBehavior;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextArea;

public abstract class MooEditableAjaxButton extends AjaxFallbackButton {

	Form<?> form;
	
	public MooEditableAjaxButton(String id, Form<?> form) {
		super(id, form);
		this.form = form;
	}
	
	@Override
	protected IAjaxCallDecorator getAjaxCallDecorator() {
		return new AjaxCallDecorator() {
	        @Override
	        public CharSequence decorateScript(final CharSequence script) {
	        		StringBuffer sb = new StringBuffer();
	        		final List<TextArea<String>> list = new ArrayList<TextArea<String>>();
	        		form.visitFormComponents(new AbstractVisitor() {
						@Override @SuppressWarnings("unchecked")
						protected void onFormComponent(FormComponent<?> fc) {
							if (fc instanceof TextArea) {
								TextArea<String> textarea = (TextArea<String>) fc;
								for (IBehavior behavior : textarea.getBehaviors()) {
									if (behavior.getClass().equals(MooEditableBehavior.class)) {
										list.add(textarea);
									}
								}
							}
						}
	        		});
	        		
	        		for (TextArea<String> textarea : list) {
	        			sb.append(textarea.getMarkupId() + ".saveContent(); ");
	        		}
	                return sb.toString() + script;
	        }
		};
	}
	
	

}
